<?php require_once(BASEPATH.'application/controllers/validaciones.php');
class Tiket extends Controller {

	var $estado;
	var $prioridad;
	var $modulo;

	function Tiket(){
		parent::Controller();
		$this->load->library("rapyd");
		$this->rapyd->set_connection('venezuela');
		$this->rapyd->load_db();
		
		$this->estado=array(
		"N"=>"Nuevo",
		"P"=>"Pendiente",
		"R"=>"Resueltos",
		"C"=>"Cerrado");

		$this->prioridad=array(
		"1"=>"Muy Alta",
		"2"=>"Alta",
		"3"=>"Media",
		"4"=>"Baja",
		"5"=>"Muy baja");
		}

	function index(){
		redirect("supervisor/tiket/filteredgrid");
	}
	function filteredgrid(){
		$this->rapyd->load("datafilter","datagrid");
 		$modbus=array(
			'tabla'   =>'usuario',
			'columnas'=>array(
			'us_codigo' =>'C&oacute;digo',
			'us_nombre'=>'Nombre'),
			'filtro'  =>array('us_nombre'=>'nombre'),
			'retornar'=>array('us_codigo'=>'usuario'),
			'titulo'  =>'Buscar Usuario');

		$filter = new DataFilter("Filtro de Tikets");
		$select=array("usuario","contenido","prioridad","estado","IF(estado='N','Nuevo',IF(estado='R','Resuelto',IF(estado='P','Pendiente','Cerrado')))as testado","estampa","id","actualizado","numero");		
		$filter->db->select($select);
		$filter->db->from('tiket_fyco');
		//$filter->db->orderby('estampa','desc');
		$filter->db->where('padre',"S");

		$filter->id = new inputField("N&uacute;mero", "id");
		$filter->id->size=11;

		$filter->estampa = new dateonlyField("Fecha", "estampa");
		$filter->estampa->clause  ="where";
		$filter->estampa->operator="=";
		//$filter->estampa->insertValue = date("Y-m-d");

		$filter->estado = new dropdownField("Estado", "estado");
		$filter->estado->option("","Todos");
		$filter->estado->options($this->estado);

		$filter->prioridad = new dropdownField("Prioridad", "prioridad");
		$filter->prioridad->option("","Todos");
		$filter->prioridad->options($this->prioridad);

		$filter->usuario = new inputField("C&oacute;digo de usuario", "usuario");
		$filter->usuario->size=11;
		$filter->usuario->append($this->datasis->modbus($modbus));

		$filter->contenido = new inputField("Contenido", "contenido");
		//$filter->contenido->clause ="likesensitive";
		//$filter->contenido->append("Sencible a las Mayusc&uacute;las");

		$filter->buttons("reset","search");
		$filter->build();
		
		function boton($estado=''){
			if($estado=='R'){
				return '1';
			}else{
				return '2';
			}
		}

		$grid = new DataGrid("Lista de Tikets");
		$grid->per_page = 10;
		$grid->order_by("estampa","DESC");
		$grid->use_function('boton');
		
		$link=anchor("supervisor/tiket/ver/<#id#>", "<#numero#>");
		$uri_2 = img(array('src'=>'images/<boton><#estado#></boton>.gif','border'=>'0','alt'=>'Estado','height'=>'12','title'=>'Estado'));	
		
		$grid->column('Acci&oacute;n',$uri_2);
		$grid->column_orderby("N&uacute;mero",$link,"id");
		$grid->column_orderby("Fecha de Ingreso","<dbdate_to_human><#estampa#>|d/m/Y h:m:s</dbdate_to_human>","estampa");
		$grid->column_orderby("Actualizado","<dbdate_to_human><#actualizado#>|d/m/Y h:m:s</dbdate_to_human>","actualizado");
		//$grid->column("Actualizado","<dbdate_to_human><#actualizado#>|d/m/Y h:m:s</dbdate_to_human>");
		$grid->column_orderby("Usuario","usuario","usuario");
		$grid->column("Contenido","contenido");
		$grid->column_orderby("Prioridad","prioridad","prioridad");
		$grid->column_orderby("Estado","testado","testado","align='LEFT'");

		$grid->add("supervisor/tiket/dataedit/create");
		$grid->build('datagridST');
		//$grid->build();
		//echo $grid->db->last_query();
		
		$extras = '
		<script type="text/javascript">
		//<![CDATA[
		(function() {
			var mySt = new superTable("demoTable", {
			cssSkin : "sSky",
			fixedCols : 1,
			headerRows : 1,
			onStart : function () {	this.start = new Date();},
			onFinish : function () {document.getElementById("testDiv").innerHTML += "Finished...<br>" + ((new Date()) - this.start) + "ms.<br>";}
			});
		})();
		//]]>
		</script>
		';
		
		$style ='
		<style type="text/css">
		.fakeContainer { /* The parent container */
		    margin: 5px;
		    padding: 0px;
		    border: none;
		    width: 900px; /* Required to set */
		    height: 320px; /* Required to set */
		    overflow: hidden; /* Required to set */
		}
		</style>	
		';
		
		$data['style']   = $style;
		$data['extras']  = $extras;
		$data['style']  .= style('superTables.css');
		$data['content'] = $grid->output;
		$data['filtro']  = $filter->output;
		$data['script']  = script('jquery.js');
		$data["script"] .= script('superTables.js');
		$data["head"]    = script("jquery.pack.js").script("plugins/jquery.numeric.pack.js").script("plugins/jquery.floatnumber.js").$this->rapyd->get_head();
		$data['title']   = '<h1>Control de Tikets</h1>';
		$this->load->view('view_ventanas', $data);
	}

	function dataedit(){
		$parametros = $this->uri->uri_to_assoc(4);
		$this->rapyd->load("dataedit");

		$edit = new DataEdit("Tiket", "tiket_fyco");
		$edit->pre_process('insert','_pre_insert');
		$edit->pre_process('delete','_pre_del');
		$edit->post_process("insert","_post_insert");
		$edit->post_process("update","_post_update");
		$edit->post_process("delete","_post_del");

		$edit->contenido = new textareaField("Contenido", "contenido");
		$edit->contenido->rule = "required";
		$edit->contenido->rows = 6;
		$edit->contenido->cols = 90;

		$edit->padre = new inputField(" ", "padre");
		$edit->padre->style='display: none;';
		$edit->padre->type='hidden';
		$edit->padre->when= array("create");

		if(!array_key_exists('pertenece',$parametros)) {

			//$edit->back_url = site_url("supervisor/tiket/filteredgrid");
			$edit->back_uri="supervisor/tiket/filteredgrid";
			$edit->padre->insertValue='S';

			$edit->prioridad = new dropdownField("Prioridad", "prioridad");
			$edit->prioridad->options($this->prioridad);
			$edit->prioridad->insertValue=5;

			$edit->estado = new inputField(" ", "estado");
			$edit->estado->style='display: none;';
			$edit->estado->type='hidden';
			$edit->estado->when= array("create");
			$edit->estado->insertValue='N';
		}else{
			//$edit->back_url = site_url("supervisor/tiket/ver/").$parametros['pertenece'];
			$edit->back_uri="supervisor/tiket/ver/".$parametros['pertenece'];
			$edit->padre->insertValue='N';

			$edit->pertenece = new inputField(" ", "pertenece");
			$edit->pertenece->style='display: none;';
			$edit->pertenece->type='hidden';
			$edit->pertenece->when= array("create");
			$edit->pertenece->insertValue=$parametros['pertenece'];
		}

		$edit->buttons("modify", "save", "undo", "delete",'back');
		$edit->build();

		$data['content'] =$edit->output;
		$data["head"]    = $this->rapyd->get_head();
		$data['title']   ='<h1>Crear Tiket</h1>';
		$this->load->view('view_ventanas', $data);
	}

	function estapriori($status,$id=NULL){
		$this->rapyd->load("dataedit");

		$edit = new DataEdit("Tiket", "tiket_fyco");
		$edit->post_process("update","_post_update");
		$edit->back_url = site_url("supervisor/tiket/ver/$id");

		$edit->prioridad = new dropdownField("Prioridad", "prioridad");
		$edit->prioridad->options($this->prioridad);

		$edit->estado = new dropdownField("Estado", "estado");
		$edit->estado->options($this->estado);

		$edit->buttons("modify", "save", "undo", "back");
		$edit->build();

		$data['content'] =$edit->output;
		$data["head"]    = $this->rapyd->get_head();
		$data['title']   ='<h1>Cambiar estado o prioridad</h1>';
		$this->load->view('view_ventanas', $data);
	}

	function ver($id=NULL){

		$DB=$this->load->database('venezuela',TRUE);
		$this->rapyd->load("datatable");
		
		if(empty($id)) redirect("supervisor/tiket/filteredgrid");
		$query = $DB->query("SELECT prioridad,estado FROM tiket_fyco WHERE $id=$id");
		$estado=$prioridad='';
		if ($query->num_rows() > 0){
			$row = $query->row();
			$prioridad = $row->prioridad;
			$estado    = $row->estado;
		}
		$link=anchor('/supervisor/tiket/dataedit/delete/<#id#>','borrar');

		$table = new DataTable(null);
		$table->cell_attributes = 'style="vertical-align:middle;"';
		$select=array("usuario","contenido","prioridad","estado","estampa","id","padre","pertenece","IF(padre='S','marco4','marco3')AS marco");

		$table->db->select($select);
		//$table->db->select("usuario,contenido,prioridad,estado,estampa,id,padre,pertenece");
		$table->db->from("tiket_fyco");
		//$table->db->where("id",$id or 'pertenece',$id);
		$table->db->where('id',$id);
		$table->db->or_where('pertenece',$id);
		$table->db->orderby("id");
		$this->db->_escape_char='';
		$this->db->_protect_identifiers=false;

		$table->per_row  = 1;
		$table->per_page = 50;
		
		$table->cell_template = "<div class='<#marco#>' ><#contenido#><br><b class='mininegro'>&nbsp;<dbdate_to_human><#estampa#>|d/m/Y h:m:s</dbdate_to_human> Usuario: <#usuario#></b></div><br>";
		$table->build();
		//echo $table->db->last_query();

		$prop=array('type'=>'button','value'=>'Agregar','name'=>'mas'  ,'onclick' => "javascript:window.location='".site_url("supervisor/tiket/dataedit/pertenece/$id/create")."'");
		$form=form_input($prop);

		$prop2=array('type'=>'button','value'=>'Cambiar estado o prioridad','name'=>'mas'  ,'onclick' => "javascript:window.location='".site_url("supervisor/tiket/estapriori/modify/$id")."'");
		$form2=form_input($prop2);

		$prop3=array('type'=>'button','value'=>'Regresar','name'=>'mas'  ,'onclick' => "javascript:window.location='".site_url("supervisor/tiket/filteredgrid")."'");
		$form3=form_input($prop3);

		$data['content']  = "<br>Prioridad: <b>".$this->prioridad[$prioridad]."</b>, Estado: <b>".$this->estado[$estado]."</b><br>";
		$data['content'] .= $table->output.$form.$form2.$form3;
		$data["head"]     = $this->rapyd->get_head().style('marcos.css').style('estilos.css');
		$data['title']    = "<h1>Tiket N&uacute;mero: $id</h1> ";
		$this->load->view('view_ventanas', $data);
	}
	function _post_insert($do) {
		$DB=$this->load->database('venezuela',TRUE);
		$pertenece=$do->get('pertenece');
		$padre=$do->get('padre');
		$id=$do->get('id');
		
		$mSQL="UPDATE tiket_fyco SET estado='P', actualizado=CURRENT_TIMESTAMP() WHERE id=$pertenece";
		$mSQL_1="UPDATE tiket_fyco SET estampa=CURRENT_TIMESTAMP() WHERE id=$id";
		$DB->simple_query($mSQL);
		$DB->simple_query($mSQL_1);
		
		IF($padre=='S'){
			$numero=$this->datasis->fprox_numero('nstiket');
			$mSQL_2="UPDATE tiket_fyco SET numero='$numero' WHERE id=$id AND padre='S'";
			$DB->simple_query($mSQL_2);
		}	
	}

	function _post_update($do) {
		$DB=$this->load->database('venezuela',TRUE);
		$pertenece=$do->get('pertenece');
		if(empty($pertenece)) $pertenece=$do->get('id');
		$mSQL="UPDATE tiket_fyco SET actualizado=CURRENT_TIMESTAMP() WHERE id=$pertenece";
		$DB->simple_query($mSQL);
	}
	function _pre_insert($do) {
		$do->set('usuario', $this->session->userdata('usuario'));
	}

	function _post_del($do){
		$DB=$this->load->database('venezuela',TRUE);
		$numero=$do->get('id');
		$sql = "DELETE FROM tiket_fyco WHERE pertenece=$numero";
		$DB->query($sql);
	}
}
?>
